package com.qf.controller;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.qf.pojo.TbGoodsType;
import com.qf.pojo.TbUser;
import com.qf.service.GoodsTypeService;
import com.qf.service.impl.GoodsTypeServiceImpl;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/*
 *@Description:
 *@author:刘哥
 *@Date:86180 2022/8/16 16:47
 */
@WebServlet("/type")
public class GoodsTypeServlet extends BaseServlet{
    private GoodsTypeService goodsTypeService=new GoodsTypeServiceImpl();

//    type?method=findAll
    public String findAll(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //        设置json编码格式
        response.setContentType("application/json;charset=UTF-8");

//        优化从application里面获取(已保存)
        ServletContext application = request.getServletContext();
//        获取application里面的goodsTypes
        List<TbGoodsType> goodsType= (List<TbGoodsType>) application.getAttribute("goodsType");
//        if (goodsType != null) {
//            response.getWriter().write(goodsType);
//            System.out.println("从application中获取");
//            return null;
//        }

//        GoodsTypeService goodsService=new GoodsTypeServiceImpl();
//        List<TbGoodsType> tbGoodsType=goodsService.findALL(1);
        String json = JSON.toJSONString(goodsType);
        response.getWriter().write(json);
//        application.setAttribute("goodsType", json);
//        ObjectMapper objectMapper = new ObjectMapper();
//        String json = objectMapper.writeValueAsString(goodsType);
        return null;

    }


//    /type?method=add
    public String add(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        TbUser admin = (TbUser) request.getSession().getAttribute("admin");
        if (admin == null) {
            return "redirect:/admin/login.jsp";
        }
        String name = request.getParameter("name");
        goodsTypeService.addGoodsType(name);
        return "redirect:/type?method=find";

    }



//    type?method=find
    public String find(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        TbUser admin = (TbUser) request.getSession().getAttribute("admin");
        if (admin == null) {
            return "redirect:/admin/login.jsp";
        }
        List<TbGoodsType> goodsTypeList = goodsTypeService.find();
        ServletContext servletContext = request.getServletContext();
//        List<TbGoodsType> goodsTypeList = (List<TbGoodsType>) servletContext.getAttribute("goodsTypeList");
        servletContext.setAttribute("goodsTypeList",goodsTypeList);
        return "redirect:/admin/showGoodsType.jsp";

    }

}
